<template>
  <section id="message-trend" class="py-20 px-4 md:px-8 bg-neutral-800/50">
    <div class="container mx-auto">
      <h2 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold mb-12 text-center">
        <span class="bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-400">年度活跃趋势</span>
      </h2>

      <div class="bg-neutral-900/70 backdrop-blur-sm rounded-2xl p-6 md:p-8 shadow-xl border border-white/5">
        <div class="flex flex-col lg:flex-row gap-8">
          <!-- 图表部分 -->
          <div ref="chartSection" class="lg:w-2/3 chart-section">
            <div class="h-[350px] w-full">
              <canvas ref="chartCanvas"></canvas>
            </div>
          </div>

          <!-- 数据统计部分 -->
          <div ref="statsSection" class="lg:w-1/3 flex flex-col justify-center stats-section">
            <div class="space-y-6 flex flex-wrap">
              <!-- 活跃成员数 -->
              <div ref="activeMembersStat" class="stat-item bg-neutral-800/50 rounded-xl p-5 border border-white/5">
                <h3 class="text-lg font-semibold mb-2">活跃成员数</h3>
                <div class="flex items-center gap-3">
                  <div class="w-12 h-12 rounded-full bg-blue-500/20 flex items-center justify-center">
                    <i class="fa fa-line-chart text-blue-400 text-xl">30</i>
                  </div>
                  <div>
                    <p class="text-sm text-neutral-400">总人数：125</p>
                    <p class="text-xs text-neutral-500">活跃人数较之前明显下降</p>
                  </div>
                </div>
              </div>

              <!-- 活跃度变化 -->
              <div ref="activityChangeStat" class="stat-item bg-neutral-800/50 rounded-xl p-5 border border-white/5">
                <h3 class="text-lg font-semibold mb-2">活跃度变化</h3>
                <div class="flex items-center gap-3">
                  <div class="w-12 h-12 rounded-full bg-green-500/20 flex items-center justify-center">
                    <i class="fa fa-arrow-up text-green-400 text-xl">降</i>
                  </div>
                  <div>
                    <p class="text-sm text-neutral-400">较去年同期</p>
                    <p class="text-xs text-neutral-500">活跃度显著下降，望继续努力！</p>
                  </div>
                </div>
              </div>

              <!-- 年度总结 -->
              <div ref="yearSummary" class="stat-item">
                <h3 class="text-lg font-semibold mb-3">不活跃总结</h3>
                <p class="text-neutral-300">活跃人数不足、无明确讨论方向、</p>
              </div>
            </div>
          </div>
        </div>
        <!-- 装饰元素 -->
        <div class="absolute -top-20 -left30 w-64 h-64 bg-purple-500/10 rounded-full blur-3xl"></div>
        <div class="absolute -bottom-32 -right20 w-80 h-80 bg-blue-500/10 rounded-full blur-3xl"></div>
      </div>
    </div>
  </section>
</template>

<script setup>
import {ref, onMounted, onUnmounted, nextTick} from 'vue'
import Chart from 'chart.js/auto';

// 为各内容块创建ref
const chartSection = ref(null)
const statsSection = ref(null)
const activeMembersStat = ref(null)
const activityChangeStat = ref(null)
const yearSummary = ref(null)

// 存储所有要动画的元素ref
const animateItems = ref([])

const chartCanvas = ref(null)
const chartInstance = ref(null) // 用于存储图表实例

onMounted(() => {
  nextTick(() => {
    // 收集所有要动画的元素ref
    animateItems.value = [
      chartSection.value,
      statsSection.value,
      activeMembersStat.value,
      activityChangeStat.value,
      yearSummary.value
    ].filter(Boolean) // 过滤掉null

    if (animateItems.value.length === 0) return
    // 配置Intersection Observer
    const observerOptions = {
      root: null,
      rootMargin: '0px 0px -20% 0px', // 当元素顶部进入视口20%时触发
      threshold: 0.1
    }
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry, index) => {
        if (entry.isIntersecting) {
          // 为每个元素设置不同的动画延迟
          const delay = index * 200 // 每个元素延迟200ms

          setTimeout(() => {
            entry.target.classList.add('item-visible')
            observer.unobserve(entry.target)
          }, delay)
        }
      })
    }, observerOptions)
    // 开始观察所有元素
    animateItems.value.forEach(item => {
      observer.observe(item)
    })

    // 单独处理图表初始化，确保在所有DOM操作完成后执行
    initChart()
  })
})

// 优化后的图表初始化函数
const initChart = () => {
  if (!chartCanvas.value) return

  // 先销毁可能存在的旧图表实例
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }

  const ctx = chartCanvas.value.getContext('2d')

  if (!ctx) {
    console.error('无法获取CanvasRenderingContext2D')
    return
  }

  chartInstance.value = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ['超1个月', '超2个月', '超3个月', '超6个月', '超12个月'],
      datasets: [{
        label: '不活跃人数',
        data: [15, 7, 30, 26, 17],
        borderColor: '#4F46E5',
        backgroundColor: 'rgba(79, 70, 229, 0.1)',
        fill: true,
        tension: 0.4,
        borderWidth: 3,
        pointBackgroundColor: '#fff',
        pointBorderColor: '#4F46E5',
        pointBorderWidth: 2,
        pointRadius: 4,
        pointHoverRadius: 6
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        },
        tooltip: {
          backgroundColor: 'rgba(17, 24, 39, 0.8)',
          titleColor: '#fff',
          bodyColor: '#fff',
          borderColor: 'rgba(255, 255, 255, 0.2)',
          borderWidth: 1,
          padding: 12,
          displayColors: false,
          callbacks: {
            label: function (context) {
              return `未发言人数: ${context.raw} 人`
            }
          }
        }
      },
      scales: {
        x: {
          grid: {
            display: false,
            drawBorder: false
          },
          ticks: {
            color: 'rgba(255, 255, 255, 0.7)'
          }
        },
        y: {
          grid: {
            color: 'rgba(255, 255, 255, 0.1)',
            drawBorder: false
          },
          ticks: {
            color: 'rgba(255, 255, 255, 0.7)',
            callback: function (value) {
              return value >= 1000 ? value / 1000 + 'k' : value
            }
          }
        }
      }
    }
  })
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }
})
</script>

<style scoped>
/* 初始样式 - 隐藏并定位在下方 */
.chart-section, .stats-section, .stat-item {
  opacity: 0;
  transform: translateY(30px);
  transition: opacity 0.6s cubic-bezier(0.5, 0, 0, 1),
  transform 0.6s cubic-bezier(0.5, 0, 0, 1);
  will-change: opacity, transform;
}

/* 可见样式 */
.chart-section.item-visible,
.stats-section.item-visible,
.stat-item.item-visible {
  opacity: 1;
  transform: translateY(0);
}

/* 统计项进入后添加额外动画 */
.stat-item.item-visible {
  transition-delay: 0.2s; /* 统计项额外延迟，增强层次感 */
}
</style>
